import os
from reportlab.lib import colors, pagesizes
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import (
    SimpleDocTemplate,
    Paragraph,
    Spacer,
    Table,
    TableStyle,
    PageBreak,
    Image as PdfImage
)

from book import Book, ContentType, TableContent
from utils import LOG

class Writer:
    def __init__(self):
        # 初始化设置，如有需要可在此添加
        pass

    def save_translated_book(self, book: Book, output_file_path: str = None, file_format: str = "PDF"):
        file_format = file_format.lower()
        if file_format == "pdf":
            return self._save_translated_book_as_pdf(book, output_file_path)
        elif file_format == "markdown":
            return self._save_translated_book_as_markdown(book, output_file_path)
        else:
            raise ValueError(f"Unsupported file format: {file_format}")

    def _save_translated_book_as_pdf(self, book: Book, output_file_path: str = None):
        if output_file_path is None:
            output_file_path = book.pdf_file_path.replace(".pdf", "_translated.pdf")

        LOG.info(f"原PDF路径: {book.pdf_file_path}")
        LOG.info(f"翻译后的PDF路径: {output_file_path}")

        # 注册中文字体
        font_path = "../fonts/simsun.ttc"  # 请将此路径替换为您的字体文件路径
        pdfmetrics.registerFont(TTFont("SimSun", font_path))

        # 创建 PDF 文档
        doc = SimpleDocTemplate(output_file_path, pagesize=pagesizes.letter)
        styles = getSampleStyleSheet()
        story = []

        # 处理每一页
        for page in book.pages:
            last_y = 0  # 起始 y 坐标
            for content in page.contents:
                # 获取当前块的坐标
                current_x0, current_y0, current_x1, current_y1 = content.position
                content_height = current_y1 - current_y0
                

                # 如果不是第一页或第一个块，则插入间距
                #if last_y != 0:
                spacing = current_y0 - last_y 
                if spacing > 0 and last_y !=0 :
                    story.append(Spacer(width=0, height=spacing))
                    
                # LOG.debug("-------------------")
                # LOG.debug(f"块之间的间距: {spacing}")
                # LOG.debug(f"当前块的坐标: {content.position}")
                # LOG.debug(f"上一个块的 y 位置: {last_y}")
                # LOG.debug(f"计算的间距: {spacing}")
                if content.content_type==ContentType.TEXT:
                     LOG.debug(f"块内容: {content.original}")
                # 处理不同类型的内容
                if content.content_type == ContentType.TEXT:
                    para_style = ParagraphStyle("SimSun", fontName="SimSun", fontSize=content.font_size)
                    text = content.translation if content.status else content.original
                    paragraph = Paragraph(text, para_style)
                    story.append(paragraph)

                elif content.content_type == ContentType.TABLE:
                    pdf_table = self._generate_pdf_table(content)
                    story.append(pdf_table)

                elif content.content_type == ContentType.IMAGE:
                    img = PdfImage(content.image_path)
                    img.drawHeight = content.height
                    img.drawWidth = content.width
                    story.append(img)

                last_y = current_y1

            # 每页后添加分页符
            if page != book.pages[-1]:
                story.append(PageBreak())

        # 保存 PDF 文件
        doc.build(story)
        LOG.info(f"翻译完成: {output_file_path}")
        return output_file_path

    def _save_translated_book_as_markdown(self, book: Book, output_file_path: str = None):
        if output_file_path is None:
            output_file_path = book.pdf_file_path.replace(".pdf", "_translated.md")

        LOG.info(f"原PDF路径: {book.pdf_file_path}")
        LOG.info(f"翻译后的Markdown路径: {output_file_path}")

        with open(output_file_path, "w", encoding="utf-8") as output_file:
            # 处理每一页
            for page in book.pages:
                for content in page.contents:
                    if content.content_type == ContentType.TEXT:
                        text = content.translation if content.status else content.original
                        output_file.write(text + "\n\n")
                        
                    elif content.content_type == ContentType.TABLE:
                        markdown_table = content.generate_markdown_table(use_translation=True)
                        output_file.write(markdown_table)
                        
                    elif content.content_type == ContentType.IMAGE:
                        output_file.write(f"![Image {content.image_name}]({content.image_name})\n\n")

                # 每页后添加分隔符
                if page != book.pages[-1]:
                    output_file.write("---\n\n")

        LOG.info(f"翻译完成: {output_file_path}")
        return output_file_path

    def _generate_pdf_table(self, table_content: TableContent):
        """
        根据 TableContent 生成 PDF 表格
        """
        data = []
        col_widths = []
        row_heights = []

        for row in table_content.data:
            row_data = []

            # 初始化列宽
            if not col_widths:
                col_widths = [cell.width for cell in row.cells]

            for cell in row.cells:
                cell_content = cell.translation if cell.status else cell.original
                row_data.append(cell_content)

            data.append(row_data)
            row_heights.append(row.cells[0].heigth)  # 假设每个单元格高度相同

        # 创建表格
        table = Table(data, colWidths=col_widths, rowHeights=row_heights)

        # 设置表格样式
        table_style = TableStyle([
            ("GRID", (0, 0), (-1, -1), 1, colors.black),
            ("ALIGN", (0, 0), (-1, -1), "CENTER"),
        ])

        for row_idx, row in enumerate(table_content.data):
            for col_idx, cell in enumerate(row.cells):
                font_size = cell.font_size if cell.font_size else 10  # 默认字体大小
                font_name = "SimSun" if cell.is_bold else "SimSun"
                table_style.add("FONTNAME", (col_idx, row_idx), (col_idx, row_idx), font_name)
                table_style.add("FONTSIZE", (col_idx, row_idx), (col_idx, row_idx), font_size)

        table.setStyle(table_style)

        return table
